//
//  下载图片
//  Created by 石虎 on 17/6/18.
//  Copyright © 2017年 石虎. All rights reserved.
//
#import "ViewController.h"

//创建图片地址
#define URL  @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497842327410&di=ac2a6e0a6bd2dcc7330f234393a4ea8e&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F160106%2F14-160106152915B2.jpg"

@interface ViewController ()

//显示的图片
@property (strong, nonatomic) UIImageView *imageView;
//点击下载图片按钮
@property (strong, nonatomic) UIButton *downloadBtn;
@end


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //1.创建图片控件
    _imageView =[[UIImageView alloc]initWithFrame:CGRectMake(30, 20, self.view.frame.size.width-60, 450)];
    //图片背景颜色
    _imageView.backgroundColor=[UIColor lightGrayColor];
    //把图片添加到视图 View 上面
    [self.view addSubview:_imageView];
    
    //2.创建下载图片按钮
    _downloadBtn=[[UIButton alloc]initWithFrame:CGRectMake(100, 500, 120, 30)];
    //按钮上面添加文字
    [_downloadBtn setTitle:@"点击下载图片" forState:UIControlStateNormal];
    //字体颜色
    [_downloadBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    //字体背景
    _downloadBtn.backgroundColor=[UIColor lightGrayColor];
    //按钮点击事件
    [_downloadBtn addTarget:self action:@selector(imageClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_downloadBtn];
}

-(void)imageClick
{
    NSLog(@"--->>图片按钮被点击了！！！");
    _downloadBtn.backgroundColor=[UIColor redColor];
    
    [_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    //根据字符串生成url对象
    NSURL *url=[NSURL URLWithString:URL];
    //创建多线程
    NSThread *thread =[[NSThread alloc]initWithTarget:self selector:@selector(downLodImage:) object:url];
    //开启线程
    [thread start];
    
}

-(void)downLodImage:(NSURL*)url
{
    //根据url获取图片的二进制数据
    NSData *data=[NSData dataWithContentsOfURL:url];
    UIImage *imageView2=[UIImage imageWithData:data];
    [self performSelectorOnMainThread:@selector(imageRefresh:) withObject:imageView2 waitUntilDone:NO];
}
//刷新主线程
-(void)imageRefresh:(UIImage*)image
{
    //全局图片
    _imageView.image=image;
}

@end
